<?php
/**
 * Description of Theme
 *
 * @author Soul_man
 */
class Theme extends X3_Module_Table {

    public $encoding = 'UTF-8';
    /*
     * uncomment if want new model functional
     */
    public $tableName = 'data_theme';
    public static $parent = array();
    
    public $_fields = array(
        'id'=>array('integer[10]','unsigned','primary','auto_increment'),
        'mainheader' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//main tile
        'maintile' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//main tile
        'back' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//background
        'cover' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//cover of pages
        'header' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//header decor
        'menu' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//menu header
        'menutile' => array('file', 'default' => 'NULL', 'allowed' => array('jpg', 'gif', 'png', 'jpeg'), 'max_size' => 10240),//main tile
        'title'=>array('string[255]','language'),
        'decorations'=>array('boolean','default'=>'1'), //page decor
        'created_at'=>array('integer[10]','unsigned','default'=>'0'),
    );

    public function fieldNames() {
        return array(
            'mainheader' => 'Шапка сайта',
            'maintile' => 'Боковые полосы',
            'back' => 'Задний фон',
            'cover' => 'Фон для страниц где текст',
            'header' => 'Декор для заголовков',
            'menu' => 'Фон для заголовков в меню',
            'menutile' => 'Шаблон декора в меню (по бокам)',
            'title'=>'Название темы',
            'decorations'=>'Декорации (Иммитация бумаги)'
        );
    }
    
    public function filter() {
        return array(
            'allow'=>array(
                'admin'=>array('list','add','clone','delete'),
            ),
            'deny'=>array(
                '*'=>array('*')
            )
        );
    }
    
    public function moduleTitle() {
        return 'Темы';
    }

    public function cache() {
        return array(
            //'cache'=>array('actions'=>'show','role'=>'*','expire'=>'+1 day'),
            'nocache'=>array('actions'=>'*','role'=>'admin')
        );
    }

    public function actionList(){
        if(!X3::user()->isAdmin())
            throw new X3_404();
        $count = Theme::num_rows();
        $paginator = new Paginator('Theme',$count);
        $models = Theme::get(array(
            '@limit'=>$paginator->limit,
            '@offset'=>$paginator->offset
        ));
        $this->template->render('list',array('models'=>$models,'paginator'=>$paginator));
    }
    
    public function getImage() {
        if(!empty($this->mainheader))
            return $this->mainheader;
        elseif(!empty($this->cover))
            return $this->cover;
        elseif(!empty($this->back))
            return $this->back;
        elseif(!empty($this->header))
            return $this->header;
        elseif(!empty($this->menutile))
            return $this->menutile;
        elseif(!empty($this->menu))
            return $this->menu;
        return null;
    }
    
    public function actionAdd() {
        $page = null;
        if(isset($_GET['id'])){
            $page = Theme::getByPk((int)$_GET['id']);
            X3::app()->theme = array(
                'mainheader'=>$page->mainheader?"/uploads/Theme/".$page->mainheader:'/images/header.gif',
                'header'=>$page->header?"/uploads/Theme/".$page->header:'/images/hr01.png',
                'menutile'=>$page->menutile?"/uploads/Theme/".$page->menutile:'/images/menutile.gif',
                'menuheader'=>$page->menu?"/uploads/Theme/".$page->menu:'/images/menuheader.gif',
                'cover'=>$page->cover?"/uploads/Theme/".$page->cover:'/images/page_background.jpg',
                'back'=>$page->back?"/uploads/Theme/".$page->back:'/images/bg1.png',
                'columntile'=>$page->maintile?"/uploads/Theme/".$page->maintile:'/images/dekor.jpg',
                'decor'=>$page->decorations == 1,
            );
        }
        if($page == null)
            $page = new Theme();
        if(isset($_POST['Theme'])){
            $page->acquire($_POST['Theme']);
            $u = new Upload($page,'mainheader');if($u->message==null){$u->save();}else{$page->addError('mainheader',$u->message);}
            $u = new Upload($page,'header');if($u->message==null){$u->save();}
            $u = new Upload($page,'maintile');if($u->message==null){$u->save();}
            $u = new Upload($page,'menutile');if($u->message==null){$u->save();}
            $u = new Upload($page,'menu');if($u->message==null){$u->save();}
            $u = new Upload($page,'cover');if($u->message==null){$u->save();}
            $u = new Upload($page,'back');if($u->message==null){$u->save();}
            $page->decorations = isset($_POST['Theme']['decorations'])?'1':'0';
            if($page->id>0)
                $page->getTable()->setIsNewRecord(false);
            if($page->save()){
                $url = "/theme/add/id/$page->id";
                if(isset($_GET['back'])){
                    $url = "/" . trim($_GET['back'],"/ ") . "?theme_id=$page->id";
                }
                $this->redirect($url);
            }
        }
        $this->template->render('form',array('model'=>$page));
    }
    
    public function actionDelete(){
        if(isset($_GET['id']) && X3::user()->isAdmin()){
            if(!isset($_POST['confirm'])){
                if(isset($_POST['cancel']))
                    $this->redirect($_POST['back']);
                $this->template->render('@layouts:confirm.php',array('title'=>'Подтверждение на удаление','back'=>$_SERVER['HTTP_REFERER'],'text'=>'Вы действительно хотите удалить эту тему оформления?'));
            }else{
                $id = (int)$_GET['id'];
                Theme::deleteByPk($id);
                if(IS_AJAX)
                    exit;
                $this->redirect(isset($_POST['back'])?$_POST['back']:$_SERVER['HTTP_REFERER']);;
            }
        }else
            throw new X3_404();
    }
    
    public function parentM() {
        if(!isset(self::$parent[$this->parent_id]))
            self::$parent[$this->parent_id] = Page::getByPk($this->parent_id);
        return self::$parent[$this->parent_id];
    }
    
    public function menu() {
        /*if(isset($_GET['parent_id'])){
            $current = $_GET['parent_id'];
            $html = array('<a href="/admin/page/"><b>Все</b></a>');
        }else{
            $current = -1;
            $html = array('<span><b>Все</b></span>');
        }
        if($current == 0)
            $html []= '<span>Верхний уровень</a>';
        else
            $html []= '<a href="/admin/page/parent_id/0">Верхний уровень</a>';
        if($current>0){
            $html []= "<span>$this->short_title</span>";
        }
        return implode(' &gt; ', $html);*/
    }
    
    public function getDefaultScope() {
        $query = array('@order'=>'title, created_at DESC');
        return $query;
    }
    
    public function onDelete($tables, $condition) {
        if (strpos($tables, $this->tableName) !== false) {
            $model = $this->table->select('*')->where($condition)->asObject(true);
            $files = array($model->mainheader,$model->maintile,$model->back,$model->cover,$model->header,$model->menu,$model->menutile);
            Uploads::cleanUp($model, $files);
            X3::db()->query("UPDATE data_page SET theme_id=NULL WHERE theme_id=$model->id");
        }
        parent::onDelete($tables, $condition);
    }    

    public function beforeValidate() {
        if($this->created_at == 0)
            $this->created_at = time();
    }
    public static function newInstance($class=__CLASS__) {
        return parent::newInstance($class);
    }
    public static function getInstance($class=__CLASS__) {
        return parent::getInstance($class);
    }
    public static function get($arr=array(),$single=false,$class=__CLASS__) {
        return parent::get($arr,$single,$class);
    }
    public static function getByPk($pk,$class=__CLASS__) {
        return parent::getByPk($pk,$class);
    }
    public static function update($fields, $params = array(), $class = __CLASS__) {
        return parent::update($fields, $params, $class);
    }
    public static function delete($params = array(), $class = __CLASS__) {
        return parent::delete($params, $class);
    }
    public static function deleteByPk($pk, $class = __CLASS__) {
        return parent::deleteByPk($pk, $class);
    }
    public static function num_rows($params = array(), $class = __CLASS__) {
        return parent::num_rows($params, $class);
    }
}
?>
